﻿using HCMS.Const;
using HCMS.DomainServiceManage.Cache.Manage;
using HCMS.Extensions;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;

namespace HCMS.Web.Manage.ServicesExtensions.SignalExt
{
    /// <summary>
    /// SignalR 服务器中心 
    /// </summary>
    /// <remarks>
    ///  系统消息 Hub
    /// </remarks>
    public class SystemMsgHub : Hub
    {
        private readonly AdminCacheManager adminCacheManager;

        public SystemMsgHub(AdminCacheManager adminCacheManager)
        {
            this.adminCacheManager = adminCacheManager;
        }

        /// <summary>
        /// 客户连接成功时触发
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            var cid = Context.ConnectionId;

            // 将当前登录连接 Id 添加到 当前管理员所在组
            //await Groups.AddToGroupAsync(cid, Context.User.FindFirstValue(ManageConst_ClaimTypes.Id));

            // 根据 id 获取指定客户端
            //var client = Clients.Client(cid);

            // 向指定用户发送消息
            //await client.SendAsync("Self", cid);

            // 向所有用户发送消息
            //await Clients.All.SendAsync("ReceiveMessage", cid, "加入了聊天");

            await adminCacheManager.SetOnlineStatus(Context.User.FindFirstValue(ManageConst_ClaimTypes.Id).ToInt(0), "1");
        }

        /// <summary>
        /// 客户断开连接时触发
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var cid = Context.ConnectionId;

            //await Groups.RemoveFromGroupAsync(cid, Context.User.FindFirstValue(ManageConst_ClaimTypes.Id));

            await adminCacheManager.SetOnlineStatus(Context.User.FindFirstValue(ManageConst_ClaimTypes.Id).ToInt(0), "0");
        }
    }
}
